package com.demo.use.varHandle;

import lombok.Getter;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

/**
 * @author XuYang
 * @since 2025/2/19 18:36
 */
@Getter
public class VarEntity {
    int value;
    String str;

    public void addValue(int value) {
        Unsafe.VALUE.getAndAdd(this, value);
    }

    public void setStr(String str) {
        Unsafe.STR.set(this, str);
    }

    public static class Unsafe {
        private static final VarHandle VALUE;
        private static final VarHandle STR;

        static {
            try {
                MethodHandles.Lookup l = MethodHandles.lookup();
                VALUE = l.findVarHandle(VarEntity.class, "value", int.class);
                STR = l.findVarHandle(VarEntity.class, "str", String.class);
            } catch (ReflectiveOperationException e) {
                throw new ExceptionInInitializerError(e);
            }
        }
    }
}
